import Vue from 'vue';

import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routerFunc = require.context('../page', true, /router.js$/);

//列出所有路由文件
const routerList = routerFunc.keys();

//keepAlive 是否缓存，isAuth 是否需要登录才有权限
let routeMapList = [],
  routeMap = [];
routerList.forEach(function(val) {
  const itemRouter = routerFunc(val).default;
  if (Array.isArray(itemRouter)) {
    itemRouter.forEach((item) => {
      routeMapList.push(item);
    });
  } else {
    routeMapList.push(itemRouter);
  }
});

// 递归路由组装
const routerEach = function(item) {
  if (item.meta && item.meta.title != undefined) {
    item.title = item.meta.title;
  }
  if (item.menu) {
    if (item.children.length > 0) {
      item.children.forEach((val) => {
        let isPath = /^\//g.test(val.path);
        if (item.group) {
          val.group = item.group;
        }
        if (!isPath) {
          val.path = item.path + '/' + val.path;
        }
        if (val.meta.title != undefined && val.meta.title != '') {
          val.title = val.meta.title;
        }
        if (val.children && val.children.length > 0) {
          routerEach(val);
        }
      });
    } else if (item.children.length === 1) {
      item = {
        ...item.children[0],
        children: [],
      };
    }
    return item;
  }
};

routeMapList.forEach((item) => {
  if (item.menu) {
    let resRouer = routerEach(item);
    if (resRouer) routeMap.push(resRouer);
  }
});
routeMapList.push({
  path: '*',
  menu: false,
  redirect: '/index',
});
const path = window.location.pathname.split('/');
export default function createRouter() {
  return new VueRouter({
    mode: 'history',
    base: '/',
    routes: routeMapList,
  });
}
